package xyz.ibenben.zhongdian.common.intercepter;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import xyz.ibenben.zhongdian.common.exception.ExceptionEnum;
import xyz.ibenben.zhongdian.common.exception.MyException;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.service.sys.SysUserService;

/**
 * @author chenjian
 * @since 2017年10月18日下午5:17:22
 */
public class CustomToken extends SimpleCredentialsMatcher {
    private SysUserService sysUserService;

    /**
     * 构造函数
     *
     * @param sysUserService 参数
     */
    public CustomToken(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    /**
     * 处理匹配
     *
     * @param authcToken 参数
     * @param info       参数
     * @return 返回值
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken authcToken,
                                      AuthenticationInfo info) {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        SysUser user = sysUserService.selectByUsername(token.getUsername());
        Object accountCredentials = getCredentials(info);

        // 将密码加密与系统加密后的密码校验，内容一致就返回true,不一致就返回false
        boolean result;
        try {
            result = user.getPassword().equals(accountCredentials.toString());
        } catch (Exception e) {
            throw new MyException(ExceptionEnum.SYSTEMERROREXCEPTION, e);
        }
        return result;
    }

}